#
# R native model objects
#

createModelObject = function(property, descriptors){
	object = list()

	object$propertyId = property@id

	object$getPropertyId = function(self){
		return (self$propertyId)
	}

	descriptorIdList = character(0)
	for(descriptor in descriptors){
		descriptorIdList = c(descriptorIdList, descriptor@id)
	}

	object$descriptorIdList = descriptorIdList

	object$getDescriptorIdList = function(self){
		return (self$descriptorIdList)
	}

	object$prepareNewData = function(self, values){
		propertyId = self$getPropertyId(self)
	
		newdata = data.frame(propertyId, NA)
	
		descriptorIdList = self$getDescriptorIdList(self)
		descriptorIdList = sapply(descriptorIdList, function(x) gsub("[ ,-]", "_", x))
	
		for(i in 1:length(descriptorIdList)){
			newdata[descriptorIdList[i]] = values[i]
		}
		
		return (newdata)
	}

	return (object)
}

createRegressionObject = function(property, descriptors, lmmodel){
	object = createModelObject(property, descriptors)

	object$lmmodel = lmmodel

	object$getSummary = function(self){
		return (paste("Linear regression (rank ", self$lmmodel$rank, ")", sep = ""))
	}

	object$evaluate = function(self, values){
		newdata = self$prepareNewData(self, values)

		return (predict(self$lmmodel, newdata = newdata))
	}
	
	return (object)
}

createRandomForestObject = function(property, descriptors, rfmodel){
	object = createModelObject(property, descriptors)

	object$rfmodel = rfmodel

	object$getSummary = function(self){
		return (paste("Random forest (", self$rfmodel$type , ")", sep = ""))
	}

	object$evaluate = function(self, values){
		require("randomForest")

		newdata = self$prepareNewData(self, values)

		return (predict(self$rfmodel, newdata = newdata))
	}

	return (object)
}